Fraction to Recurring Decimal
Question
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return “0.5”.
Given numerator = 2, denominator = 1, return “2”.
Given numerator = 2, denominator = 3, return “0.(6)”.
Analysis
主要难点在于如何找到小数点后的循环部分,并将其以正确的形式写出。
- 利用hashmap记录已有的小数点后数字及其对应下标
- 将原本的输入变量转换为long型,以免后续操作中出现溢出的状况。
- 通过异或(^)判断最终结果是否为负
- 每次求得余数remain,在下一次处理remain/denom的时候需要*10,已保证每次进行操作的被除数都包含整数部分。
- 当在hashmap中发现已存的小数时,找到第一个重复remain的下标tmp。则substring(0,tmp)为重复小数部分之前的部分,而substring(tmp,len(result))则为剩余应该包含在括号内的部分。
Code
|
|
3Sum Closest
Question
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Analysis
- 最后返回加和,不需要保存下标,故只需保存与target差距最小的值max
- 对数组排序后,在low<high的条件下,判断当前和值与target的差值是否小于max,是则赋值,否则若sum<target,移动low下标,否则移动high下表
Code
|
|